//
//  LoginViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/1/16.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "V4LoginViewController.h"
//#import "LJImageRollingView.h"
//#import "SelectWebUrlViewController.h"
#import "V4RegisterViewController.h"
#import <ShareSDK/ShareSDK.h>
#import "WXApi.h"
#import <TencentOpenAPI/QQApiInterface.h>
//#import <ShareSDKExtension/ShareSDKExtension.h>
#import <ShareSDKExtension/ShareSDK+Extension.h>

@interface V4LoginViewController ()<UITextFieldDelegate>{//LJImageRollingViewDelegate
    UIView *viewBG;
    UITextField *txtAccount;
    UITextField *txtPwd;
    
    UIButton *subBtn;
    float viewH;
    
    BOOL boolLogin;
    UIImageView *imageLogo;
    
    UIScrollView*scrollView;
    //    LJImageRollingView *imageRolling;
}

@end

@implementation V4LoginViewController


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //注册监听键盘事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleDefault];
    txtAccount.text=[[Utility Share] userAccount];
    txtPwd.text=[[Utility Share] userPwd];
    [[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleDefault];
    
    //    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //
    //
    //        dispatch_async(dispatch_get_main_queue(), ^{
    //
    //
    //        });
    //    });
    
    [self passConTextChange:nil];
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initComponents];
    
    
    
    [txtAccount addTarget:self  action:@selector(passConTextChange:)  forControlEvents:UIControlEventEditingChanged];
    [txtPwd addTarget:self  action:@selector(passConTextChange:)  forControlEvents:UIControlEventEditingChanged];
    
}

-(void)passConTextChange:(UITextField*)tf{
    if (([txtAccount.text notEmptyOrNull])&&([txtPwd.text notEmptyOrNull])) {
        
        subBtn.backgroundColor=rgb(223, 171, 34);
    }else{
        subBtn.backgroundColor=rgb(236, 205, 122);
    }
    
    
}


- (void)initComponents{
    self.view.backgroundColor=zrgbwhiteColor;
    scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, kTopHeight, kScreenWidth, kScreenHeight-kTopHeight)];
    [self.view addSubview:scrollView];
    UILabel*lbTitle=[RHMethods ClableY:10 W:kScreenWidth Height:17 font:17 superview:scrollView withColor:nil text:@"使用账号和密码登录"];
    scrollView.contentHeight=lbTitle.frameYH;
    
    {
        UIView*viewContent=[RHMethods viewWithFrame:CGRectMake(0, scrollView.contentHeight+34, kScreenWidth, 40) backgroundcolor:nil superView:scrollView];
       [RHMethods imageviewWithFrame:CGRectMake(20, 11, 12, 18) defaultimage:@"mobicon" supView:viewContent];
        UITextField*tfmobile=[RHMethods textFieldlWithFrame:CGRectMake(81, 0, kScreenWidth-10-81, 40) font:Font(14) color:nil placeholder:@"请输入手机号" text:@""];
        [viewContent addSubview:tfmobile];
        tfmobile.delegate=self;
        scrollView.contentHeight=viewContent.frameYH;
        
        txtAccount=tfmobile;
    }
    {
        UIView*viewContent=[RHMethods viewWithFrame:CGRectMake(0, scrollView.contentHeight+20, kScreenWidth, 40) backgroundcolor:nil superView:scrollView];
        [RHMethods imageviewWithFrame:CGRectMake(20, 11, 12, 15) defaultimage:@"pasicon" supView:viewContent];
        UITextField*tfmobile=[RHMethods textFieldlWithFrame:CGRectMake(81, 0, kScreenWidth-10-81, 40) font:Font(14) color:nil placeholder:@"请输入密码" text:@""];
        [viewContent addSubview:tfmobile];
        tfmobile.delegate=self;
        scrollView.contentHeight=viewContent.frameYH;
        [RHMethods viewWithFrame:CGRectMake(20, viewContent.frameHeight-0.5, kScreenWidth-40, 0.5) backgroundcolor:rgb(229,229,229) superView:viewContent];
        txtPwd=tfmobile;
        txtPwd.secureTextEntry=YES;
    }
     WSSizeButton*btnlogin=[RHMethods buttonWithframe:CGRectMake(20, scrollView.contentHeight+32, kScreenWidth-40, 40) backgroundColor:rgb(236,205,122) text:@"登录" font:17 textColor:zrgbwhiteColor radius:4 superview:scrollView];
    subBtn=btnlogin;
    
     [subBtn addTarget:self action:@selector(submintButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel*lbforget=[RHMethods lableX:20 Y:btnlogin.frameYH+8 W:150 Height:12 font:12 superview:scrollView withColor:rgb(102,102,102) text:@"忘记密码?"];
    UIButton*btnPwd=[[UIButton alloc]initWithFrame:lbforget.frame];
    [lbforget.superview addSubview:btnPwd];
    
    [btnPwd addTarget:self action:@selector(pwdButtonClicekd) forControlEvents:UIControlEventTouchUpInside];
     UILabel*lbregest=[RHMethods RlableRX:20 Y:lbforget.frameY W:150 Height:12 font:12 superview:scrollView withColor:rgb(223,171,34) text:@"立即注册"];
    UIButton*btnRegister=[[UIButton alloc]initWithFrame:lbregest.frame];
    [lbregest.superview addSubview:btnRegister];
    [btnRegister addTarget:self action:@selector(registerButtonClicekd) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel*lbdsf=[RHMethods ClableY:0 W:kScreenWidth Height:12 font:12 superview:scrollView withColor:rgb(51,51,51) text:@"第三方登录"];
    lbdsf.frameBY=140;
  
    
    
    
    WSSizeButton*btnwx=[RHMethods buttonWithframe:CGRectMake(0, lbdsf.frameYH+15, 40, 40) backgroundColor:nil text:@"" font:0 textColor:nil radius:0 superview:scrollView];
    [btnwx setBackgroundImage:[UIImage imageNamed:@"v4wxicon"] forState:UIControlStateNormal];
    
    WSSizeButton*btnqq=[RHMethods buttonWithframe:CGRectMake(0, lbdsf.frameYH+15, 40, 40) backgroundColor:nil text:@"" font:0 textColor:nil radius:0 superview:scrollView];
    [btnqq setBackgroundImage:[UIImage imageNamed:@"v4qqicon"] forState:UIControlStateNormal];
    btnwx.frameXW=kScreenWidth/2-22;
    btnqq.frameX=kScreenWidth/2+22;
    
      BOOL isInstallWx = [ShareSDK isClientInstalled:SSDKPlatformTypeWechat];
    BOOL isInstallQQ=[ShareSDK isClientInstalled:SSDKPlatformTypeQQ];
//    btnwx.hidden=!isInstallWx;
//    btnqq.hidden=!isInstallQQ;
    
    
    [btnwx addTarget:self action:@selector(wxButtonClicekd) forControlEvents:UIControlEventTouchUpInside];
    [btnqq addTarget:self action:@selector(QQButtonClicekd) forControlEvents:UIControlEventTouchUpInside];
    
    if (btnwx.hidden) {
        [btnqq beCX];
    }
    if (btnqq.hidden) {
        [btnwx beCX];
    }
    if (btnwx.hidden&&btnqq.hidden) {
        lbdsf.hidden=YES;
    }
    
    
    [[Utility Share] setIsUserLogin:NO];
    
    
    boolLogin=NO;
    
    [self isLoginStatus];
    
    [self passConTextChange:nil];

}
-(void)welcomeLoginAdvertising{
    ////    XKFwelcome
    //    [NetEngine createGetAction_LJ:XKFV3homesad onCompletion:^(id resData, BOOL isCache) {
    //        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
    //            NSMutableArray *arrayA=[NSMutableArray new];
    //            for (NSDictionary *dc in [[resData objectForJSONKey:@"data"] objectForJSONKey:@"list"]) {
    //                NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:dc];
    //                [dic setValue:[dc valueForJSONStrKey:@"2x_path"] forKey:@"url"];
    //                [arrayA addObject:dic];
    //            }
    //            [imageRolling reloadImageView:arrayA selectIndex:0];
    //        }else{
    //            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
    //        }
    //    }];
}
-(void)isLoginStatus{
    
    [self performSelector:@selector(hiddenTransitionView) withObject:self afterDelay:0.5];
    
}
-(void)hiddenTransitionView{
    [[Utility Share] hiddenStartTransitionView];
}
-(void)hiddenTransitionView_OnlyOne{
    [[Utility Share] hiddenStartTransitionView];
    
}
#pragma mark button
-(void)submintButtonClicked{
    boolLogin=YES;
    
    
    [self closeButtonClicked];
    
    //    //分享授权
    //    if ([ShareSDK hasAuthorized:SSDKPlatformTypeSinaWeibo]) {
    //        [ShareSDK cancelAuthorize:SSDKPlatformTypeSinaWeibo];
    //    }
    
    NSString *strAc=txtAccount.text;
    NSString *strPwd=txtPwd.text;
    
    if (![strAc notEmptyOrNull])
    {
        [SVProgressHUD showImage:nil status:@"请填写账号"];
        return;
    }
    
    if (![strPwd notEmptyOrNull])
    {
        [SVProgressHUD showImage:nil status:@"密码不能为空"];
        return;
    }
    [[Utility Share] isLoginAccount:strAc pwd:strPwd code:nil aLogin:^(NSInteger NoLogin) {
        if (NoLogin==1) {
            
            
        }
        
    }];
    
    
    
    
    
    
    
}
-(void)closeButtonClicked{
    [txtAccount resignFirstResponder];
    [txtPwd resignFirstResponder];
    
}

#pragma mark text
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField==txtAccount) {
        [txtPwd becomeFirstResponder];
    }else{
        [self submintButtonClicked];
    }
    return YES;
}


#pragma mark serlector
-(void)handleKeyboardDidShow:(NSNotification *)notification{
    
    NSDictionary *info = [notification userInfo];
    CGRect keyboardFrame;
    [[info objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;
    CGFloat distanceToMove = kbSize.height;
    NSLog(@"---->动态键盘高度:%f",distanceToMove);
    if (distanceToMove<20) {
        return;
    }
    float t_y=(Y(viewBG)+distanceToMove +YH(subBtn)+10)-kScreenHeight;
    
    NSLog(@"---->动态键盘高度:%f:::::<%f",distanceToMove,t_y);
    
    [UIView animateWithDuration:0.3 animations:^{
        viewBG.frame=CGRectMake(X(viewBG), Y(viewBG) - t_y, W(viewBG),H(viewBG));
        
    }];
}
- (void)handleKeyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.3 animations:^{
        viewBG.frame=CGRectMake(X(viewBG), (kScreenHeight-viewH)/2.0, W(viewBG),H(viewBG));
        
        
    }];
}//


//#pragma mark LJImageRollingViewDelegate
//-(void)selectView:(LJImageRollingView *)selectView ad:(NSDictionary *)dic index:(NSInteger)index{
//    if ([[dic valueForJSONStrKey:@"links"] notEmptyOrNull]) {
//         [self pushController:[SelectWebUrlViewController class] withInfo:@"" withTitle:@"" withOther:@{@"url":[dic valueForJSONStrKey:@"links"]}];
//    }
//}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

//是否支持屏幕旋转
-(BOOL)shouldAutorotate
{
    return NO;
}

// 支持的旋转方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    
    return UIInterfaceOrientationMaskPortrait;//UIInterfaceOrientationMaskAllButUpsideDown;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    
    return UIInterfaceOrientationPortrait;
}
#pragma mark - v4 button
-(void)registerButtonClicekd{
    [self pushController:[V4RegisterViewController class] withInfo:@"register" withTitle:@"立即注册" withOther:nil];
}
-(void)pwdButtonClicekd{
    [self pushController:[V4RegisterViewController class] withInfo:@"pwd" withTitle:@"找回密码" withOther:nil];
}
-(void)wxButtonClicekd{
    [self otherTypeLogin:SSDKPlatformTypeWechat];
    //
}
-(void)QQButtonClicekd{
    [self otherTypeLogin:SSDKPlatformTypeQQ];
}
-(void)otherTypeLogin:(SSDKPlatformType)type{
    NSMutableDictionary *dicT=[NSMutableDictionary new];
    if (type==SSDKPlatformTypeQQ) {
        [dicT setValue:@"qq" forKey:@"type"];
    }else if(type==SSDKPlatformTypeWechat){
        [dicT setValue:@"weixin" forKey:@"type"];
        
    }
    
    [ShareSDK getUserInfo:type
           onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
     {
         if (state == SSDKResponseStateSuccess)
         {
             [dicT setValue:user.uid forKey:@"openid"];
             [dicT setValue:user.nickname forKey:@"nickname"];
             [dicT setValue:user.icon forKey:@"icon"];
             [self loginThirdPartyShareSDK:dicT];
             [ShareSDK cancelAuthorize:type];
         }else if (state==SSDKResponseStateFail){
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"登录失败"
                                                             message:[NSString stringWithFormat:@"%@",error]
                                                            delegate:nil
                                                   cancelButtonTitle:@"OK"
                                                   otherButtonTitles:nil, nil];
             [alert show];
         }else
         {
             NSLog(@"%@",error);
         }
         
     }];
}

-(void)loginThirdPartyShareSDK:(NSDictionary *)dic{
    DLog(@"_________dic:%@",dic);
    [NetEngine createPostAction:XKFV4welcometposlogin withParams:dic onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            NSDictionary *userDict = [resData objectForJSONKey:@"data"];
            [[Utility Share] setUserId:[userDict valueForJSONStrKey:@"uid"]];
            [[Utility Share] setUserToken:[userDict valueForJSONStrKey:@"token"]];
            //            [[Utility Share] setUserInfo:userDict];
            [[Utility Share] saveUserInfoToDefault];
            [[Utility Share] setUserIsADD:[[userDict valueForJSONStrKey:@"type"] isEqualToString:@"4"]];//type    int        用户类型(1
            [[Utility Share] hiddenLoginAlert:YES];
        }else if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"201"]){
            
            [self pushController:[V4RegisterViewController class] withInfo:@"other" withTitle:@"绑定手机" withOther:[resData objectForJSONKey:@"data"]];
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    }];
    
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
